import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword (pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
      letters[pass[i]] = (letters[pass[i]] || 0) + 1
      score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
      digits: /\d/.test(pass),
      lower: /[a-z]/.test(pass),
      upper: /[A-Z]/.test(pass),
      nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (var check in variations) {
      variationCount += (variations[check] === true) ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

/**
 * @name 处理文件地址
 * @param { String } path
 * @returns
 */
export function formatUrl (path) {
  const linkReg = /https?:\/\//i
  const baseUrl = process.env.VUE_APP_API_BASE_URL
  return linkReg.test(path) ? path : (path.indexOf(baseUrl) === -1 ? (baseUrl + path) : path)
}

/**
 * @name 系统附件流形式文件下载
 * @param url
 * @returns {Promise<unknown>}
 */
export function downloadFile (url, params) {
  return new Promise((resolve, reject) => {
    // 两个参数，url下载路径， fileName 文件名
    var xhr = new XMLHttpRequest()
    url = process.env.VUE_APP_API_BASE_URL + url
    // 组合参数
    if (typeof params === 'object') {
      const queryObject = JSON.parse(JSON.stringify(params))
      let paramsStr = '?'
      for (const key in queryObject) {
        paramsStr += key
        paramsStr += '='
        paramsStr += queryObject[key]
        paramsStr += '&'
      }
      paramsStr = paramsStr.substr(0, paramsStr.length - 1)
      url += paramsStr
    }
    // GET请求,请求路径url,async(是否异步)
    xhr.open('GET', url, true)
    // 设置请求头参数的方式,如果没有可忽略此行代码
    xhr.setRequestHeader('Authorization', storage.get(ACCESS_TOKEN))
    // 设置响应类型为 blob
    xhr.responseType = 'blob'
    // 关键部分
    xhr.onload = function (e) {
      // 如果请求执行成功
      if (this.status === 200) {
        const blob = this.response
        const a = document.createElement('a')
        // blob.type = "application/octet-stream"
        // 创键临时url对象
        var url = URL.createObjectURL(blob)
        // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
        const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        const contentDisposition = decodeURI(xhr.getResponseHeader('content-disposition'))
        const result = patt.exec(contentDisposition)
        const filename = typeof params === 'object' || params === undefined ? result[1] : params
        console.log('filename', filename)
        a.href = url
        a.download = filename || '列表.xlsx'
        a.click()
        // 释放之前创建的URL对象
        window.URL.revokeObjectURL(url)
        resolve(this.response)
      } else {
        reject(this.response)
      }
    }
    // 发送请求
    xhr.send()
  })
}

/**
 * @name 获取格式化的日期
 * @param {*} date
 * @returns
 */
export function getDate (date, format = 'yyyy-MM-dd hh:mm:ss', char = '-') {
	if (date === undefined || date === '') date = new Date()
  const formatMap = [
    'yyyy-MM-dd', 'yyyy-MM-dd hh:mm:ss',
    'text', 'text hh:mm:ss',
    'empty', 'yyyy-MM-dd hh:mm',
    'yyyy-MM'
  ]
  if (formatMap.includes(date)) {
    format = date
    date = new Date()
  }
  if (!(date instanceof Date)) {
    date = new Date(date.replace(/-/g, '/'))
  }
  const YYYY = date.getFullYear()
  const MM = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
  const DD = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
  const hh = date.getHours() > 9 ? date.getHours() : '0' + date.getHours()
  const mm = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
  const ss = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
  switch (format) {
    case formatMap[0]: return `${YYYY}${char}${MM}${char}${DD}`
    case formatMap[1]: return `${YYYY}${char}${MM}${char}${DD} ${hh}:${mm}:${ss}`
    case formatMap[2]: return `${YYYY}年${MM}月${DD}日`
    case formatMap[3]: return `${YYYY}年${MM}月${DD}日 ${hh}:${mm}:${ss}`
    case formatMap[4]: return `${YYYY}${MM}${DD}${hh}${mm}${ss}`
    case formatMap[5]: return `${YYYY}${char}${MM}${char}${DD} ${hh}:${mm}`
    case formatMap[6]: return `${YYYY}${char}${MM}`
  }
}
